﻿/*
    Copyright (c) 2007 - 2009, Carlos Guzmán Álvarez

    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, 
    are permitted provided that the following conditions are met:

        * Redistributions of source code must retain the above copyright notice, 
          this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright notice, 
          this list of conditions and the following disclaimer in the documentation and/or 
          other materials provided with the distribution.
        * Neither the name of the author nor the names of its contributors may be used to endorse or 
          promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using Framework.Net.Xmpp.Core;
using Framework.Net.Xmpp.Serialization.Extensions.MultiUserChat;
using Framework.Net.Xmpp.Serialization.InstantMessaging.Client.Presence;

namespace Framework.Net.Xmpp.InstantMessaging
{
    /// <summary>
    /// Represents a conversation in a conference room
    /// </summary>
	public sealed class XmppChatRoom
    {
        #region · Fields ·

        private XmppSession             session;
        private XmppJid                 chatRoomId;
        private IList<XmppChatRoomUser> users;
        private XmppChatRoomFeatures    features;
        private XmppService             conferenceService;
        private AutoResetEvent          seekEnterChatRoomEvent;
        private AutoResetEvent          createChatRoomEvent;
        private bool                    seekAllowed;
        private bool                    createAllowed;
        private string                  lastMessageId;

        #endregion

        #region · Properties ·

        /// <summary>
        /// Gets the session.
        /// </summary>
        /// <value>The session.</value>
        public XmppSession Session
        {
            get { return this.session; }
        }

        /// <summary>
        /// Gets the chat room id.
        /// </summary>
        /// <value>The chat room id.</value>
        public XmppJid ChatRoomId
        {
            get { return this.chatRoomId; }
        }

        /// <summary>
        /// Gets the users.
        /// </summary>
        /// <value>The users.</value>
        public ReadOnlyCollection<XmppChatRoomUser> Users
        {
            get { return new ReadOnlyCollection<XmppChatRoomUser>(this.users); }
        }

        /// <summary>
        /// Gets the features.
        /// </summary>
        /// <value>The features.</value>
        public XmppChatRoomFeatures Features
        {
            get { return this.features; }
        }

        #endregion

        #region · Constructors ·

        /// <summary>
        /// Initializes a new instance of the <see cref="T:XmppChatRoom"/> class.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="conferenceService">The conference service.</param>
        /// <param name="chatRoomId">The chat room id.</param>
        internal XmppChatRoom(XmppSession session, XmppService conferenceService, XmppJid chatRoomId)
		{
            this.session                                = session;
            this.conferenceService                      = conferenceService;
            this.chatRoomId                             = chatRoomId;
            this.seekEnterChatRoomEvent                 = new AutoResetEvent(false);
            this.createChatRoomEvent                    = new AutoResetEvent(false);
            this.users                                  = new List<XmppChatRoomUser>();

            // this.session.SessionStateChanged            += new EventHandler(OnSessionClosing);
            //this.session.MultiUserChatMessageReceived   += new EventHandler<XmppMessageReceivedEventArgs>(OnMultiUserChatMessageReceived);
		}

        #endregion

        #region · Internal Methods ·

        internal bool SeekEnterChatRoom()
        {
            Presence presence = new Presence();

            this.seekAllowed    = false;
            this.lastMessageId  = XmppIdentifierGenerator.Generate();

            presence.Id     = this.lastMessageId;
            presence.From   = this.session.UserId.ToString();
            presence.To     = this.chatRoomId.ToString();

            presence.Items.Add(new MultiUserChatProtocol());

            this.session.Send(presence);

            this.seekEnterChatRoomEvent.WaitOne();

            return this.seekAllowed;
        }

        internal bool CreateChatRoom()
        {
            Presence presence = new Presence();

            this.createAllowed = false;
            this.lastMessageId = XmppIdentifierGenerator.Generate();

            presence.Id = this.lastMessageId;
            presence.To = this.chatRoomId.ToString();

            presence.Items.Add(new MultiUserChatProtocol());

            this.session.Send(presence);

            this.createChatRoomEvent.WaitOne();

            return this.createAllowed;
        }

        #endregion

        #region · Event Handlers ·

        private void OnMultiUserChatMessageReceived(object sender, XmppMessageReceivedEventArgs e)
        {
#warning TODO: Implement
        }

        private void OnOnSessionStateChanged(object sender, EventArgs e)
        {
#warning TODO: Implement
        }

        private void OnPresenceMessageReceived(object sender, XmppPresenceMessageReceivedEventArgs e)
        {
            if (e.Presence.Id == this.lastMessageId)
            {
                Console.WriteLine("eee");
            }
        }

		#endregion
	}
}
